package ua.com.kangaroo.parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

import ua.com.kangaroo.basic.School;
import ua.com.kangaroo.basic.SchoolsData;

public class AddressParser {
	private File addressFile;
	
	public AddressParser(String addressFileName) {
		addressFile = new File(addressFileName);
	}
	
	/**
	 * @return false if there exist some problem to parse addressFile and true if not 
	 */
	
	public boolean readFromFile(){
		Scanner FileScanner = null;
		try{
			FileScanner = new Scanner(new BufferedReader(new FileReader(addressFile)));
			FileScanner.useDelimiter("[\r\n]+|[\\|]{1}");
			while (FileScanner.hasNext()){
				int id;
				String name;
				String[] address = new String[8];
				String[] coordinator = new String[3];
				
				if (FileScanner.hasNextInt()){
					id = FileScanner.nextInt();
				} else return false;
				
				for (int i = 0; i < 3; i++) {
					if (FileScanner.hasNext()) {
						coordinator[i] = FileScanner.next();
					} else return false;
				}
				
				if (FileScanner.hasNext()) {
					address[0] = FileScanner.next();
				} else return false;
				if (FileScanner.hasNext()) {
					FileScanner.next();
				} else return false;
				for (int i = 1; i < 8; i++) {
					if (FileScanner.hasNext()) {
						address[i] = FileScanner.next();
					} else return false;
				}
				
				if (FileScanner.hasNext()) {
					name = FileScanner.next();
				} else return false;
				
				School newSchool = new School(id, name, coordinator, address);
				if (!SchoolsData.addSchool(id, newSchool)) return false;
			} 
			return true;
		} catch (IOException e) {
			return false; 
		} finally {
			if (FileScanner != null) FileScanner.close();
		}	
	}
}
